YAHOO_DATE = 1;
USER_DATE = 2;
REAL_TIME_DATE = 3;


//If Firebug is not installed, there will not be js errors :)
if (!window.console || !console.firebug)
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}


 function getQuoteNameURL(_baseUrl,_symbol)
{
  return _baseUrl +"?s="+_symbol+"&f=n";
}

 function getQuoteHistoryDataURL(_baseUrl,_dateIni, _dateFinal, _symbol)
{
	  
	var urlFinal = _baseUrl +"?a="+_dateIni.getMonth()+"&b="+_dateIni.getDate()+"&c="+_dateIni.getFullYear();
    urlFinal = urlFinal + "&d="+_dateFinal.getMonth()+"&e="+_dateFinal.getDate()+"&f="+_dateFinal.getFullYear();
    urlFinal = urlFinal + "&g=d&s="+_symbol;
    return urlFinal;
}
		
function getDateAsString(_date)
{
  if(_date == null) return "";
  return _date.getDate()+"/"+(_date.getMonth()+1)+"/"+_date.getFullYear();
}



/**
 * Given a date, this fucntion returns the closer date that allows the 
 * retrieval of stock market information 
 *   
 * @param {Object} _date
 * @param {Object} _days
 */	
function getValidDate(_date, _days,_stock)
{
	if(_date == null) return null;
	
	var date = new Date(_date.getTime());
	if(_days == null) _days = 0;
	
	date.setDate(date.getDate()- _days);
	date.setHours(0,0,0,0);
  
	var weekDay = date.getDay();
	if (weekDay==0) date.setDate(date.getDate()-2);
	if (weekDay==6) date.setDate(date.getDate()-1);

	if(isKnownStockClosedDate(_stock,date))
	{
		date = getValidDate(date,1, _stock);
	}
	
	return date;
}

function isKnownStockClosedDate(_stock,_date)
{
	var stockPos = -1;
		
	if (_stock==null)
	{
		stockPos = 0;
	}
	else
	{
		for(var j=0;j<STOCK_EXCHANGES.length;j++)
		{
			if(STOCK_EXCHANGES[j]==_stock)
			{
				stockPos = j;
				break
			}
		}
		if(stockPos == -1)  // StockEchange dates not included
			return false;
	}
	
	for(var i=0;i<STOCK_CLOSED_DATES[stockPos].length;i++)
	{
		if(STOCK_CLOSED_DATES[stockPos][i].getYear()==0)
		{
			if(STOCK_CLOSED_DATES[stockPos][i].getDate()==_date.getDate() && STOCK_CLOSED_DATES[stockPos][i].getMonth()==_date.getMonth())
				return true;
		}
		else if(STOCK_CLOSED_DATES[stockPos][i].getTime() == _date.getTime() )
		 return true;
	}
	
	return false;
}

		
function getDate(_strDate, _dateType)
{
	var strDate;
	var resDate ;
	resDate = new Date();
	
	switch(_dateType)
	{
		case YAHOO_DATE: 
						strDate = _strDate.split('-');
						if(strDate.length >= 3)
						{
							if(strDate[0].length==4) //yyyy-mm-dd
								resDate.setFullYear(strDate[0],strDate[1]-1,strDate[2]);
							else					//dd-mmm-yy
								resDate = new Date(strDate[0]+' '+strDate[1]+' 20'+strDate[2]+' ');
						}
						else
							resDate = null;
							
						break;
		case USER_DATE:	
						strDate = _strDate.split('/');
						if(strDate.length >= 3)
						{
							resDate.setFullYear(strDate[2],strDate[1]-1,strDate[0]);
						}
						else
							resDate = null;
						break;
		case REAL_TIME_DATE:	
						strDate = _strDate.split('/');
						if(strDate.length >= 3)
						{
							resDate.setFullYear(strDate[2],strDate[0]-1,strDate[1]);
						}
						else
							resDate = null;
						break;
	}
	if(resDate!=null)
		resDate.setHours(0,0,0,0);
	return resDate;
	
}

function getTableHeadTemplate(_ids,_desc)
{
	var contentData = "";
	
	contentData += '<tr class="head">';
	
	for(var i=0;i<_desc.length;i++)
	{
	  if(_ids[i]=="description")
	  {
	  	contentData+=	'<td>'+_desc[i]+'</td>';
	  }
	  else
	  {
	  	contentData+=	'<td align="center">'+_desc[i]+'</td>';	
	  }
	  
	}
	contentData += '</tr>';
	
	return contentData;
}

function getRowsTemplate(_description, _class,_moduleId,_tableFields,_qtdRows)
{
	var i=0;
	var contentData = '';
	
	contentData += getRowTemplate(_description,_class,_tableFields, _class+i+_moduleId);
	
	for(i=1;i<_qtdRows;i++)
	{
		contentData += getRowTemplate('',_class,_tableFields, _class+i+_moduleId);
	}
	
	return contentData;
}
		
function getRowTemplate(_description,_class,_tableFields, _id)
{ 
	var contentText= '';
	var i;     
	var spanName = _id;
	
	contentText += '<tr class="'+_class+'" id="'+spanName+'_tr">';
	
	for(i=0;i<_tableFields.length;i++)
	{
		if(_tableFields[i]=="description")
		{
			contentText += '<td><span id="'+spanName+'_'+_tableFields[i]+'">'+_description+'</span></td>';	
		}
		else if(_tableFields[i]=="date")
		{
			contentText += '<td align="center"><span id="'+spanName+'_'+_tableFields[i]+'"><span class="loading">Loading...</span></span></td>';		
		}
		else
		{
			contentText += '<td align="center"><span id="'+spanName+'_'+_tableFields[i]+'"></span></td>';
		}
			
	}
	
	contentText += '</tr>';
	
			
	return contentText;  
}


	
/**
 * @param {Object} _conf --> module configuration 
 * @param {Object} _id  --> Row Id. Composed by the class name ("history"||"current"||"total_invested"||"invested") and its id. E.g: "history0"
 * @param {Object} _date
 * @param {Object} _quoteValue
 * @param {Object} _investmentValue
 * @param {Object} _percent
 */



function setRowValue(_conf, _id, _fields, _values)
{
	var contentText = "";
	var color;
	var imgspan = "";
	var spanName;
      
	var spanId = _id;
	
	for(var i=0;i<_fields.length;i++)
	{
		spanName = _gel(spanId+'_'+_fields[i]);

		if(_fields[i]=="percent")
		{
			var percent = _values[i];
			imgspan = "";
			spanName.innerHTML ="";
			if(percent!=null)
			{
				if(percent<0) 
				{ 
					spanName.className='percent_down';
					imgspan = '<img src="'+_conf.moduleHostURL+'resources/down_r.gif" alt="Down" border="0" height="14" width="10">';
				}
				else if(percent>0)
		 		{
		 			spanName.className='percent_up';
		 			imgspan = '<img src="'+_conf.moduleHostURL+'resources/up_g.gif" alt="Up" border="0" height="14" width="10">';
		 		}
				else
					spanName.className='percent_still';
	
				spanName.innerHTML = imgspan;
			}
			else
				percent='-';
			spanName.innerHTML += percent;
		}
		else if(_fields[i]=="date")
		{
			if(_values[i] !=null)
				spanName.innerHTML = getDateAsString(_values[i]);	
		} 
		else if(_fields[i]=="investmentValue" )
		{
			if(_values[i] !=null && _values[i]!=0)
			{
				spanName.innerHTML = _values[i];
				if(_values[i].constructor == Number)
					spanName.innerHTML = _values[i].toFixed(2);	
			}
			else
			{
				spanName.innerHTML ="not available";
			}
				
		}else if(_fields[i]=="before" || _fields[i]=="after" || _fields[i]=="quoteValue")
		{
			if(_values[i] !=null)
			{
				spanName.innerHTML = _values[i];
				if(_values[i].constructor == Number)
					spanName.innerHTML = _values[i].toFixed(2);	
			}
			else
				spanName.innerHTML = '-';
				
		}
		else if(_fields[i]=="hint")
		{
			var percent = getFieldValue(_fields, _values, "percent");
			var investmentValue = getFieldValue(_fields, _values, "investmentValue");
			if(investmentValue != null && investmentValue ==0)
			{
				percent = null;
			}
			imgspan = "";
			if(percent!=null)
			{
				if(percent >= _conf.thresholdSell  )
				{
					imgspan = '<img src="'+_conf.moduleHostURL+'resources/pinS.gif" alt="Sell" border="0" >';
					spanName.innerHTML =imgspan;
					spanName.title ='Sell it!!!';
				}
				else
				if(percent <= _conf.thresholdBuy)
				{
					imgspan = '<img src="'+_conf.moduleHostURL+'resources/pinB.gif" alt="Buy" border="0" >';
					spanName.innerHTML =imgspan;
					spanName.title ='Buy more!!!';
				}
			}
			
		}
	}
}
	
	
	
	    
function getFieldValue(_fields, _values, _fieldName)
{
	for(var i=0;i<_fields.length;i++)
	{
		if(_fields[i]==_fieldName)
			return _values[i];
	}
	
	return null;
}
	
function getChartTabTemplate(_prefs,_tabId, _class, _id, _urlSource)
{
	
	var contentChart = '';
	 
	
	contentChart = '<div class="'+_class+'" id="'+_tabId+'">';
	contentChart += '<table border="0" cellpadding="2" cellspacing="0" width="100%">';
	contentChart += '<table id="'+_tabId+'_zoom">';
	contentChart += '<tr class="chart_legend">';
	contentChart += '<td align="right"></td>';
	//contentChart += '<td align="right"></td>';
	contentChart += '</tr></table>';
	contentChart += '<table border="0" cellpadding="2" cellspacing="0" width="100%">';
	contentChart += '<tr class="head">';
	contentChart += '<td align="center"><span id="'+_tabId+'_name"><span class="loading">Loading...</span></span></td>';
	contentChart += '<td align="center">(<span id="'+_tabId+'_link"><span class="loading">Loading...</span></span>)</td>';
	contentChart += '</tr></table>';
	contentChart +='<table align=center style="border:0;font-size: 8pt;font-family: Tahoma" width="100%" id="contentTable" cellspacing=0 cellpadding=2>';
	contentChart +='<tr>';
	contentChart +='<td align="center" title="Chart: '+_id+'"><span id="'+_tabId+'_chart"><span class="loading">Loading...</span><span></td></tr>';
	contentChart +='</table>';
	contentChart += '<table>';
	
	var sourceStr;
	var init;
	var end;
	
	init = _urlSource.indexOf('//');
	if (init==-1) init =0;
	else
	 init +=2;
	sourceStr = _urlSource.substring(init,_urlSource.length);
	
	end = sourceStr.indexOf('/');
	if (end==-1) end =sourceStr.length;
	else
	 init +=1;
	sourceStr = sourceStr.substring(0,end);
	
	
	contentChart += '<tr class="chart_legend"><td> Source: '+sourceStr;
	contentChart += '</td></tr>';
	contentChart += '</table>';
	contentChart +='</div>';
				
	return contentChart;
}


function updateChartPreferences(_pref,_timeDuration,_timeUnit, _updateChartFunction)
{
	_updateChartFunction();
}
		
function setChartTabValue(_id,_quote, _quoteUrl, _chartUrl)
{
	var tabId = _id;
		  
	var spanName= _gel(tabId+'_name');
	var spanLink = _gel(tabId+'_link');
	var spanChart = _gel(tabId+'_chart');

	spanName.innerHTML= _quote.name;
	spanLink.innerHTML= '<a href="'+_quoteUrl+'" target="blank">'+_quote.symbol+'</a>';
	spanChart.innerHTML= '<img src="'+_chartUrl+'"></td>';
	
}




function updateTableTemplate(_tableId, _qtdRecordsLoaded)
{
	var historyTable = _gel(_tableId);
	var toBeDeleted = historyTable.rows.length - _qtdRecordsLoaded;
	  
      
	for( var i = 0;i<toBeDeleted;i++)
      {
		historyTable.deleteRow(-1); //deleting last row
      }
	
}




function getPercentBaseModeString(_conf, _forceDaily)
{
	var calculPercentModeStr = "";
	
	if(_forceDaily ==null) _forceDaily=false;
	
	if(_forceDaily || _conf.history_percentBaseMode == "daily")
	{
		calculPercentModeStr = "day before";
	}
	else	
	if(_conf.history_percentBaseMode == "last_week")
	{
		calculPercentModeStr = "last week";
	}
	else
	if(_conf.history_percentBaseMode == "last_month")
	{
	    calculPercentModeStr = "last month";
	}
	else
	if(_conf.history_percentBaseMode == "last_6_month")
	{
	   calculPercentModeStr = "last 6 moths";
	}
	else
	if(_conf.history_percentBaseMode == "last_year")
	{
	   calculPercentModeStr = "last year";
	}
	else
	if(_conf.history_percentBaseMode == "last_investment")
	{
	  calculPercentModeStr = "last investement";
	}

			 
	return calculPercentModeStr;
}

function getPercentBaseDate(_conf, _lastInvestmentDate, _specificDay)
{
	var resDate = new Date();
	resDate.setHours(0,0,0,0);
			  
	if(_conf.history_percentBaseMode == "last_week")
	{
		resDate.setDate(resDate.getDate()-7);
		if(resDate.getDay()!=1)
		{
			var toMonday = resDate.getDay()-1;
			resDate.setDate(resDate.getDate()-toMonday );
		}
		resDate = getValidDate(resDate,0);
	}
	else
	if(_conf.history_percentBaseMode == "last_month")
	{
		resDate.setDate(1);
        resDate.setDate(resDate.getDate()-1);
        resDate = getValidDate(resDate,0);
	}
	else
	if(_conf.history_percentBaseMode == "last_6_month")
	{
		resDate.setMonth(resDate.getMonth()-6);
		resDate.setDate(1);
		resDate.setDate(resDate.getDate()-1);
		resDate = getValidDate(resDate,0);
	}
	else
	if(_conf.history_percentBaseMode == "last_year")
	{
		resDate.setFullYear(resDate.getFullYear()-1);
		resDate = getValidDate(resDate,0);
	}
	else
	if(_conf.history_percentBaseMode == "specific_day")
	{
		if(_specificDay == null || _specificDay=="")
		{
			_conf.history_percentBaseMode == "daily";
		}
		else
		{
			resDate = getDate(_specificDay,USER_DATE);
			resDate = getValidDate(resDate,0);	
		}
	}
	else
	if(_conf.history_percentBaseMode == "last_investment")
	{
		resDate = _lastInvestmentDate;
		resDate = getValidDate(resDate,0);
		
		if(resDate == null)
			_conf.history_percentBaseMode == "daily";
	}
	else
	if(_conf.history_percentBaseMode == "daily")
	{
		resDate = null;
	}
	 
	return resDate;
}

function  orderDescByDate(e1, e2) 
{
	if  (e1.date.getTime() < e2.date.getTime())
		return 1;
	else if (e1.date.getTime()> e2.date.getTime())
		return -1;                
    else 
		return 0;

}

function getPercentValue(_currentValue, _baseValue)
{
	var res = _currentValue /_baseValue;
	res = (res * 100) - 100;
	var percent = res.toFixed(2);
	return percent;
}

function getPercent(_quotes, _date, _baseDate)
{
	var j;
	var currentValue =0;
	var baseValue =100; //could be any value
	var percent;
	var res;
	
	if(_quotes.constructor==Quote)
	{
		var quote = _quotes;
		_quotes = new Array();
		_quotes.push(quote);
	}
	
	for(j=0;j<_quotes.length;j++)
	{
		res = getHipotheticalValue(_quotes[j],_date, _baseDate, baseValue);
		if(res ==null)
		{
			return null;
		}
		else
		 currentValue += res;
	}
	
	return getPercentValue(currentValue, baseValue);
	
}


//Given a _investedDate an an _investedValue it returns the invested value for the _date
function getHipotheticalValue(_quote,_date, _investedDate, _investedValue)
{
	var purchasedQuantity;
	var res;
	var cotation;
	var investedCotation = _quote.getCotation(_investedDate);
	
	var today = new Date();
	today.setHours(0,0,0,0);
	
	if(today.getTime() == _date.getTime())
	{
		cotation = _quote.currentCotation;
	}
	else
	{
		var cotation = _quote.getCotation(_date);
	}
	
	
	if(cotation !=null && investedCotation!=null)
			{
				_investedValue = _quote.compositionPercent * _investedValue / 100;
				purchasedQuantity = _investedValue / investedCotation.value;
				res = purchasedQuantity * cotation.value;
			}
		else
			{
				res = null;
			}

	
	return res;
	
	
}

function getToogleArrow(_conf, _tableId)
{
	var content ='';
	var imgId = _tableId+'_imageToggle';
	var funcCall = "onclick='toggleTable(\""+_tableId+"\",\""+imgId+"\",\""+_conf.moduleHostURL+"\")'";
	
	content += "<img id='"+imgId+"' src='"+_conf.moduleHostURL+"resources/arrow_show.gif' alt='Show'  border='0' "+funcCall+" />";
	
	return content;
}

function toggleTable(_tableId, _imageId, _hostPath)
{	
	var tableStyle = _gel(_tableId).style;
	
	if(tableStyle.display=="none")
	{
		tableStyle.display=""
	}
	else
		{
			tableStyle.display="none"
		}
	
	var imageSection = _gel(_imageId);
	
	if(tableStyle.display=="")
	{
		imageSection.src=_hostPath+"resources/arrow_hide.gif";
	}
	else
	{
		imageSection.src=_hostPath+"resources/arrow_show.gif";
	}
	
}

	